<?php

namespace App\Http\Controllers\Managea;

use App\Traits\BaseFun;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class PhotoController extends Controller
{

   public function TPhoto(Request $request)
   {
      $file = $request->file('file');
      if ($file->isValid()) {

         $originalName = $file->getClientOriginalName(); // 文件原名
         $ext = $file->getClientOriginalExtension();     // 扩展名
         $realPath = $file->getRealPath();   //临时文件的绝对路径
         $type = $file->getClientMimeType();     // image/jpeg

         // 上传文件
         $filename = date('Ymd') . '/' . uniqid() . '.' . $ext;

         // 使用我们新建的upload本地存储空间（目录）
         // 这里的upload是配置文件的名称
         $bool = Storage::disk('upload')->put($filename, file_get_contents($realPath));
         // var_dump($bool);die();
         $ArrDate = [
            'state' => 0,
            'data' =>
            //  'https://' . $_SERVER['HTTP_HOST'] . '/upload/' . $filename,
            ['https://' . $_SERVER['HTTP_HOST'], '/upload/' . $filename],
            'token' => $request->input('token')
         ];
         return BaseFun::jsonReturn($ArrDate);
      }
   }
   public function Upload(Request $request){//图片批量上传

        $file = $request->file('file');
        $filePath =[];  // 定义空数组用来存放图片路径
        foreach ($file as $key=>$value) {
          if ($value->isValid()) {
           $originalName = $value->getClientOriginalName(); // 文件原名
           $ext = $value->getClientOriginalExtension();     // 扩展名
           $realPath = $value->getRealPath();   //临时文件的绝对路径
           $type = $value->getClientMimeType();     // image/jpeg
           // 上传文件
           $filename = date('Ymd') . '/' . uniqid() . '.' . $ext;
           // 使用我们新建的upload本地存储空间（目录）
           // 这里的upload是配置文件的名称
           $bool = Storage::disk('upload')->put($filename, file_get_contents($realPath));
           $filePath[$key] = ['https://' . $_SERVER['HTTP_HOST'], '/upload/' . $filename];
 
          }
         }
         $ArrDate = [
            'state' => 0,
            'data' =>$filePath,
            'token' => $request->input('token')
         ];
         return BaseFun::jsonReturn($ArrDate);
        }

    // 删除图片
    public function DelPhoto(Request $request)
    {
        # 获取相对地址
        $imgUrl = $request->input('img');
        if ($imgUrl) {
            $delImg = unlink(public_path() .'/'. $imgUrl);
            if ($delImg) {
                $ArrDate = ['state' => 0, 'data' => $delImg, 'token' => $request->input('token')];
            } else {
                $ArrDate = ['state' => 2, 'data' => '', 'msg' => '获取失败!'];
            }
            return BaseFun::jsonReturn($ArrDate);
        }
    }


}
